
#include "Logger.h"


Logger::Logger(string filename, enum LogLevel lel): level(lel)
{
    pthread_mutex_init(&log_lock, NULL);  
    ofile.open(filename.c_str());
    if (!ofile)
    {
        cout << "Unable to open log file(" << filename << "). Exiting..." << endl;
        exit(1);
    }
}

Logger::~Logger()
{
    ofile.close();
    pthread_mutex_destroy(&log_lock);
}

void Logger::log(string msg, enum LogLevel lel)
{
    if (lel >= level) {
        char tmp[64]; 
        time_t t = time(0);
        strftime(tmp, sizeof(tmp), "%Y/%m/%d %X ",localtime(&t)); 
        pthread_mutex_lock(&log_lock);
	ofile << tmp;
        switch (lel) {
            case LOG_LEVEL_DEBUG:
                ofile << "[DEBUG]";
                break;
            case LOG_LEVEL_INFO:
                ofile << "[INFO]";
                break;
            case LOG_LEVEL_WARNING:
                ofile << "[WARNING]";
                break;
            case LOG_LEVEL_ERROR:
                ofile << "[ERROR]";
                break;
            case LOG_LEVEL_FATAL:
                ofile << "[FATAL]";
                break;
            default:
                break;
        }
        ofile << msg << endl;
        pthread_mutex_unlock(&log_lock);
    }
}



